package facade;

import machinery.factory.MachineryFactory;
import machinery.factory.TractorFactory;
import machinery.factory.SeederFactory;
import machinery.factory.HarvesterFactory;
import machinery.Machinery;
import machinery.state.IdleState;
import machinery.state.WorkingState;
import machinery.state.MalfunctionState;
import machinery.decorator.PrecisionGuidanceDecorator;
import machinery.decorator.AutoIrrigationDecorator;
import environment.EnvironmentMonitor;
import environment.SoilSensor;
import environment.WeatherSensor;
import environment.CropSensor;
import task.Task;
import task.TaskManager;
import pathplanning.PathPlanner;
import pathplanning.StandardPathStrategy;
import pathplanning.EmergencyPathStrategy;
import security.SecurityChain;
import security.ObstacleHandler;
import security.FaultDetectionHandler;
import security.BoundaryCheckHandler;

import java.util.ArrayList;
import java.util.List;

/**
 * 外观模式：为系统提供一个统一的接口
 */
public class FarmingSystemFacade {
    private List<Machinery> machineries;
    private EnvironmentMonitor environmentMonitor;
    private PathPlanner pathPlanner;
    private TaskManager taskManager;
    private SecurityChain securityChain;
    
    public FarmingSystemFacade() {
        this.machineries = new ArrayList<>();
        this.environmentMonitor = new EnvironmentMonitor();
        this.pathPlanner = new PathPlanner();
        this.taskManager = new TaskManager();
        this.securityChain = buildSecurityChain();
    }
    
    public void startSystem() {
        System.out.println("初始化系统组件...");
        
        // 初始化环境监测器并添加传感器
        initializeEnvironmentMonitor();
        
        // 使用工厂模式创建不同类型的农机设备
        initializeMachineries();
        
        // 为环境监测器添加观察者(农机设备)
        for (Machinery machinery : machineries) {
            environmentMonitor.addObserver(machinery);
        }
        
        // 初始化路径规划器策略
        pathPlanner.setStrategy(new StandardPathStrategy());
        
        System.out.println("系统初始化完成!");
    }
    
    private void initializeEnvironmentMonitor() {
        System.out.println("初始化环境监测系统...");
        environmentMonitor.addSensor(new SoilSensor());
        environmentMonitor.addSensor(new WeatherSensor());
        environmentMonitor.addSensor(new CropSensor());
    }
    
    private void initializeMachineries() {
        System.out.println("初始化农机设备...");
        MachineryFactory tractorFactory = new TractorFactory();
        MachineryFactory seederFactory = new SeederFactory();
        MachineryFactory harvesterFactory = new HarvesterFactory();
        
        machineries.add(tractorFactory.createMachinery());
        machineries.add(seederFactory.createMachinery());
        machineries.add(harvesterFactory.createMachinery());
    }
    
    private SecurityChain buildSecurityChain() {
        // 责任链模式：构建安全处理链
        ObstacleHandler obstacleHandler = new ObstacleHandler();
        FaultDetectionHandler faultHandler = new FaultDetectionHandler();
        BoundaryCheckHandler boundaryHandler = new BoundaryCheckHandler();
        
        obstacleHandler.setNext(faultHandler);
        faultHandler.setNext(boundaryHandler);
        
        return obstacleHandler;
    }
    
    // 新增装饰器相关方法
    public void addPrecisionGuidanceSystem(int machineryId) {
        if (machineryId >= 0 && machineryId < machineries.size()) {
            Machinery original = machineries.get(machineryId);
            // 装饰器模式：动态添加精准导航功能
            PrecisionGuidanceDecorator decorated = new PrecisionGuidanceDecorator(original);
            // 替换原有设备
            machineries.set(machineryId, decorated);
            // 更新环境监测的观察者
            environmentMonitor.removeObserver(original);
            environmentMonitor.addObserver(decorated);
            System.out.println("成功为设备添加精准导航系统");
        } else {
            System.out.println("无效的设备ID");
        }
    }
    
    public void addAutoIrrigationSystem(int machineryId) {
        if (machineryId >= 0 && machineryId < machineries.size()) {
            Machinery original = machineries.get(machineryId);
            // 装饰器模式：动态添加自动灌溉功能
            AutoIrrigationDecorator decorated = new AutoIrrigationDecorator(original);
            // 替换原有设备
            machineries.set(machineryId, decorated);
            // 更新环境监测的观察者
            environmentMonitor.removeObserver(original);
            environmentMonitor.addObserver(decorated);
            System.out.println("成功为设备添加自动灌溉系统");
        } else {
            System.out.println("无效的设备ID");
        }
    }
    
    public void usePrecisionGuidance(int machineryId) {
        if (machineryId >= 0 && machineryId < machineries.size()) {
            Machinery machinery = machineries.get(machineryId);
            if (machinery instanceof PrecisionGuidanceDecorator) {
                ((PrecisionGuidanceDecorator) machinery).optimizeRoute();
            } else {
                System.out.println("该设备未安装精准导航系统");
            }
        } else {
            System.out.println("无效的设备ID");
        }
    }
    
    public void useAutoIrrigation(int machineryId) {
        if (machineryId >= 0 && machineryId < machineries.size()) {
            Machinery machinery = machineries.get(machineryId);
            if (machinery instanceof AutoIrrigationDecorator) {
                ((AutoIrrigationDecorator) machinery).irrigate();
            } else {
                System.out.println("该设备未安装自动灌溉系统");
            }
        } else {
            System.out.println("无效的设备ID");
        }
    }
    
    public void refillWater(int machineryId) {
        if (machineryId >= 0 && machineryId < machineries.size()) {
            Machinery machinery = machineries.get(machineryId);
            if (machinery instanceof AutoIrrigationDecorator) {
                ((AutoIrrigationDecorator) machinery).refillWater();
            } else {
                System.out.println("该设备未安装自动灌溉系统");
            }
        } else {
            System.out.println("无效的设备ID");
        }
    }
    
    public void simulateOperation() {
        System.out.println("\n模拟系统运行...");
        
        // 分配任务
        System.out.println("\n-- 任务分配 --");
        taskManager.createTask("播种任务", machineries.get(1));
        taskManager.createTask("耕地任务", machineries.get(0));
        taskManager.createTask("收割任务", machineries.get(2));
        
        // 模拟环境数据变化
        System.out.println("\n-- 环境数据变化 --");
        environmentMonitor.updateSoilMoisture(85); // 土壤湿度过高
        
        // 处理安全事件
        System.out.println("\n-- 安全事件处理 --");
        securityChain.handleRequest("障碍物");
        securityChain.handleRequest("边界越界");
        securityChain.handleRequest("设备故障");
        
        // 切换路径规划策略
        System.out.println("\n-- 紧急情况路径重规划 --");
        pathPlanner.setStrategy(new EmergencyPathStrategy());
        pathPlanner.planPath(machineries.get(0), "紧急避障");
        
        // 恢复正常策略
        pathPlanner.setStrategy(new StandardPathStrategy());
        pathPlanner.planPath(machineries.get(0), "继续作业");
        
        // 使用装饰器功能
        System.out.println("\n-- 使用装饰器增强功能 --");
        // 给拖拉机添加精准导航系统
        addPrecisionGuidanceSystem(0);
        usePrecisionGuidance(0);
        
        // 给播种机添加自动灌溉系统
        addAutoIrrigationSystem(1);
        environmentMonitor.updateSoilMoisture(20); // 模拟土壤干旱，触发灌溉
        refillWater(1);
    }
    
    // 环境监测相关方法
    public void updateSoilMoisture(int moisture) {
        System.out.println("\n操作: 更新土壤湿度");
        environmentMonitor.updateSoilMoisture(moisture);
    }
    
    public void updateTemperature(int temperature) {
        System.out.println("\n操作: 更新气温");
        environmentMonitor.updateTemperature(temperature);
    }
    
    public void updateWindSpeed(int windSpeed) {
        System.out.println("\n操作: 更新风速");
        environmentMonitor.updateWindSpeed(windSpeed);
    }
    
    // 农机设备相关方法
    public void listAllMachineries() {
        System.out.println("\n当前系统中的农机设备:");
        for (int i = 0; i < machineries.size(); i++) {
            Machinery m = machineries.get(i);
            System.out.println(i + ". " + m.getName() + " (" + m.getType() + ") - " + m.getState().getStateName());
        }
    }
    
    public void showMachineryDetails(int id) {
        if (id >= 0 && id < machineries.size()) {
            Machinery m = machineries.get(id);
            System.out.println("\n设备详情:");
            System.out.println("ID: " + id);
            System.out.println("名称: " + m.getName());
            System.out.println("类型: " + m.getType());
            System.out.println("状态: " + m.getState().getStateName());
            System.out.println("油量: " + m.getFuel() + "%");
            System.out.println("位置: [" + m.getPosition()[0] + ", " + m.getPosition()[1] + "]");
            
            // 显示装饰器信息
            if (m instanceof PrecisionGuidanceDecorator) {
                System.out.println("附加功能: 精准导航系统");
            }
            if (m instanceof AutoIrrigationDecorator) {
                System.out.println("附加功能: 自动灌溉系统");
            }
        } else {
            System.out.println("无效的设备ID");
        }
    }
    
    public void changeMachineryState(int id, int stateChoice) {
        if (id >= 0 && id < machineries.size()) {
            Machinery m = machineries.get(id);
            switch (stateChoice) {
                case 1:
                    m.changeState(new IdleState());
                    break;
                case 2:
                    m.changeState(new WorkingState());
                    break;
                case 3:
                    m.changeState(new MalfunctionState());
                    break;
            }
            System.out.println(m.getName() + " 状态已更改");
        } else {
            System.out.println("无效的设备ID");
        }
    }
    
    // 任务管理相关方法
    public void createTask(String taskName, int machineryId) {
        if (machineryId >= 0 && machineryId < machineries.size()) {
            Machinery m = machineries.get(machineryId);
            taskManager.createTask(taskName, m);
        } else {
            System.out.println("无效的设备ID");
        }
    }
    
    public void listAllTasks() {
        List<Task> tasks = taskManager.getTasks();
        if (tasks.isEmpty()) {
            System.out.println("当前没有任务");
        } else {
            System.out.println("\n当前任务列表:");
            for (int i = 0; i < tasks.size(); i++) {
                Task t = tasks.get(i);
                System.out.println(i + ". " + t.getName() + " - 分配给: " + t.getAssignedMachinery().getName() + " - 状态: " + t.getStatus());
            }
        }
    }
    
    public void completeTask(int taskId) {
        List<Task> tasks = taskManager.getTasks();
        if (taskId >= 0 && taskId < tasks.size()) {
            taskManager.completeTask(tasks.get(taskId));
        } else {
            System.out.println("无效的任务ID");
        }
    }
    
    public void cancelTask(int taskId, String reason) {
        List<Task> tasks = taskManager.getTasks();
        if (taskId >= 0 && taskId < tasks.size()) {
            taskManager.failTask(tasks.get(taskId), reason);
        } else {
            System.out.println("无效的任务ID");
        }
    }
    
    // 路径规划相关方法
    public void useStandardPathPlanning(int machineryId, String taskDescription) {
        if (machineryId >= 0 && machineryId < machineries.size()) {
            System.out.println("\n使用标准路径规划:");
            pathPlanner.setStrategy(new StandardPathStrategy());
            pathPlanner.planPath(machineries.get(machineryId), taskDescription);
        } else {
            System.out.println("无效的设备ID");
        }
    }
    
    public void useEmergencyPathPlanning(int machineryId, String emergencyDescription) {
        if (machineryId >= 0 && machineryId < machineries.size()) {
            System.out.println("\n使用紧急路径规划:");
            pathPlanner.setStrategy(new EmergencyPathStrategy());
            pathPlanner.planPath(machineries.get(machineryId), emergencyDescription);
        } else {
            System.out.println("无效的设备ID");
        }
    }
    
    // 安全系统相关方法
    public void handleSecurityEvent(String eventType) {
        System.out.println("\n处理安全事件: " + eventType);
        securityChain.handleRequest(eventType);
    }
    
    // 系统状态相关方法
    public void showSystemStatus() {
        System.out.println("环境数据状态:");
        System.out.println("  - 已连接传感器数量: " + 3);
        System.out.println("  - 已连接观察者数量: " + machineries.size());
        
        System.out.println("\n农机设备状态:");
        for (Machinery m : machineries) {
            String decoratorInfo = "";
            if (m instanceof PrecisionGuidanceDecorator) {
                decoratorInfo += " [已装配精准导航]";
            }
            if (m instanceof AutoIrrigationDecorator) {
                decoratorInfo += " [已装配自动灌溉]";
            }
            System.out.println("  - " + m.getName() + ": " + m.getState().getStateName() + decoratorInfo);
        }
        
        System.out.println("\n任务状态:");
        List<Task> tasks = taskManager.getTasks();
        System.out.println("  - 总任务数: " + tasks.size());
        
        System.out.println("\n路径规划器状态:");
        if (pathPlanner.getStrategy() instanceof StandardPathStrategy) {
            System.out.println("  - 当前策略: 标准路径规划");
        } else {
            System.out.println("  - 当前策略: 紧急路径规划");
        }
    }
} 